//
//  APIbase.m
//  DoctorVideo
//
//  Created by 牛清旭 on 2019/8/13.
//  Copyright © 2019 lzx. All rights reserved.
//

#import "APIbase.h"
#import "AFNetworking.h"
#import "AFNetworkActivityIndicatorManager.h"
#import <CommonCrypto/CommonCrypto.h>
#import "TipView.h"
static id sharedNetManager = nil;
static dispatch_once_t onceToken;

@interface APIbase ()

@property(nonatomic, strong) AFHTTPSessionManager *sessionManager;

@end

@implementation APIbase


+ (instancetype)sharedNetManager
{
    dispatch_once(&onceToken, ^{
        sharedNetManager = [[super allocWithZone:NULL] init];
    });
    return sharedNetManager;
}

+ (void)tearDown{
    
    sharedNetManager =nil;
    onceToken = 0l;
    NetManagerShare.sessionManager = nil;
}

- (AFHTTPSessionManager *)sessionManager{
    
    
#if DEBUG //非正式环境
    if (!_sessionManager) {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString *baseUrl = [user objectForKey:@"baseUrl"];
        if (baseUrl== nil) {
            baseUrl = BaseUrl;
        }
        _sessionManager =[[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:baseUrl]];
    }
#else//正式
    if (!_sessionManager) {
        _sessionManager =[[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:BaseUrl]];
    }
#endif
    return _sessionManager;
}

- (NSURLSessionDataTask * )requestWithMethod:(HttpRequestType)method URLString:(NSString *)URLString parameters:(NSDictionary *)parameters done:(void (^)(NSURLSessionDataTask * , id ))done fail:(void (^)(NSURLSessionDataTask * , NSError * ))fail{
    NSString *url = [NSString stringWithFormat:@"%@%@",BaseUrl,URLString];
    URLString = url;
    NSLog(@"请求接口为-------%@ \n %@",URLString,parameters.mj_JSONString);
    
    //用于对成功后的处理
    void (^responseSuccessBlock)(NSURLSessionDataTask *task, id responseObject) = ^(NSURLSessionDataTask *task, id responseObject) {
        done(task, responseObject);
//        NSLog(@"URL:\n%@", [task.currentRequest URL].absoluteString);
//         NSLog(@"responseObject-------%@",responseObject);
//        if ([[responseObject valueForKey:@"error"]integerValue] == 2006 && ![[responseObject valueForKey:@"message"]isEqualToString:@"未知错误"]) {
//           [TipView showMessage:responseObject[@"description"]];
//            [TipView showMessage:@"登录已过期请重新登录"];
//            [[DVUserManager shareManager] logout];
//        }
    };
    
    //对失败后结果处理
    void (^responseFailBlock)(NSURLSessionDataTask *task, NSError *error)=^(NSURLSessionDataTask *task, NSError *error){
        fail(task,error);
        NSLog(@"URL:\n%@", [task.currentRequest URL].absoluteString);
        NSLog(@"error-------%@",error);

    };
    
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    
    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = YES;
    NetManagerShare.sessionManager.responseSerializer = response;
    
    AFJSONRequestSerializer *request = [AFJSONRequestSerializer serializer];
    NetManagerShare.sessionManager.requestSerializer = request;
    
    if (self.CustomRequest) {
        NetManagerShare.sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];//董森添加为了处理返回值为String
        self.CustomRequest = NO;
    }
    //设置请求头
    
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    NSString *token = [defaults objectForKey:kDVUserToken];
//    DVUserManager *userManager = [DVUserManager shareManager];
//    NSString *token = [userManager.userInfo objectForKey:kDVUserTokenKey];
//    NSDictionary *dic = @{@"keys":token?:@"940dfc883d35fc97702da1245baf8568"};
    NSDictionary *userInfo = [DVUserManager shareManager].userInfo;
    NSString *tokens = NULLString(userInfo[kDVUserTokenKey])?@"":userInfo[kDVUserTokenKey];
    NSString *uuid = [FCUUID uuidForDevice]?:@"";
    NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    NSDictionary *dic = @{@"source":@"app",
                          @"sign":@"",
                          @"version":appVersion,
                          @"app_type":@"ios",
                          @"did":uuid,
                          @"model":[DeviceInfoHander getDeviceInfo],
                          @"token":tokens
    };
    NSLog(@"token===%@",tokens);
    [self setHttpHeaderFieldDictionary:dic];
//    NSLog(@"header-------%@",dic);
    NetManagerShare.sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/css", @"text/xml", @"text/plain", @"application/javascript", @"application/x-www-form-urlencoded", @"image/*",@"multipart/form-data", nil];
    
//    [NetManagerShare.sessionManager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    NSURLSessionDataTask *task = nil;
    NetManagerShare.sessionManager.requestSerializer.timeoutInterval = 120;
    
    if (method == HttpRequestTypeGet) {
        
        task = [NetManagerShare.sessionManager GET:URLString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"后台返回数据为------%@",responseObject);
            if([responseObject isKindOfClass:[NSDictionary class]]){
                responseSuccessBlock(task, responseObject);
            }else{
                if ([responseObject isKindOfClass:[NSData class]]) {//处理字符类型的
                    NSString * result = [[ NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                    result = [result stringByReplacingOccurrencesOfString:@"\"" withString:@""];
                    responseSuccessBlock(task, result);
                }
                else{
                    
                    NSError *err=nil;
                    err = responseObject;
                    responseFailBlock(task,err);
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            responseFailBlock(task,error);
        }];
        
    }else if(method==HttpRequestTypePost){
        
//        task = [NetManagerShare.sessionManager POST:URLString parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//            
//            [NetManagerShare.sessionManager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//            
//        } progress:^(NSProgress * _Nonnull uploadProgress) {
//            
//        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            NSLog(@"后台返回数据为------%@",responseObject);
//            if ([responseObject[@"status"] integerValue] == 1) {
//                responseSuccessBlock(task,responseObject);
//            }
//            NSString *alertString = NULLString(responseObject[@"message"]) ? @"" : responseObject[@"message"];
//            [TipView showMessage:alertString];
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            [TipView showMessage:[NSString stringWithFormat:@"%@接口请求失败",URLString]];
//            responseFailBlock(task,error);
//        }];

        task = [NetManagerShare.sessionManager POST:URLString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"后台返回数据为------%@",responseObject);
            if ([responseObject[@"status"] integerValue] == 1) {
                responseSuccessBlock(task,responseObject);
            }
            NSString *alertString = NULLString(responseObject[@"message"]) ? @"" : responseObject[@"message"];
            [TipView showMessage:alertString];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [TipView showMessage:[NSString stringWithFormat:@"%@接口请求失败",URLString]];
            responseFailBlock(task,error);
        }];
        
    }else if (method == HttpRequestTypePut){
        
        task = [NetManagerShare.sessionManager PUT:URLString parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            responseSuccessBlock(task,responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            responseFailBlock(task,error);
        }];
        
//        task = [NetManagerShare.sessionManager PUT:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            responseSuccessBlock(task,responseObject);
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            responseFailBlock(task,error);
//        }];
        
    }else if (method == HttpRequestTypeDelete){
        
        task = [NetManagerShare.sessionManager DELETE:URLString parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            responseSuccessBlock(task,responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            responseFailBlock(task,error);
        }];
        
//        task = [NetManagerShare.sessionManager DELETE:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            
//            responseSuccessBlock(task,responseObject);
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            responseFailBlock(task,error);
//        }];
    }
    
    return task;
}


- (void)setHttpHeaderFieldDictionary:(NSDictionary *)httpHeaderFieldDictionary
{
    _httpHeaderFieldDictionary = httpHeaderFieldDictionary;
    
    if (![httpHeaderFieldDictionary isKindOfClass:[NSDictionary class]])
    {
        return;
    }
    NSArray *keyArray = httpHeaderFieldDictionary.allKeys;
    
    if (keyArray.count <= 0)
    {
        return;
    }
    
    for (NSInteger i = 0; i < keyArray.count; i ++)
    {
        NSString *keyString = keyArray[i];
        NSString *valueString = httpHeaderFieldDictionary[keyString];
        
        [APIbase setValue:valueString forHTTPHeaderKey:keyString];
    }
}

/**
 *  自定义请求头
 */
+ (void)setValue:(NSString *)value forHTTPHeaderKey:(NSString *)HTTPHeaderKey
{
    [NetManagerShare.sessionManager.requestSerializer setValue:value forHTTPHeaderField:HTTPHeaderKey];
}


/* 输出http响应的状态码 */
- (NSInteger)showResponseCode:(NSURLSessionDataTask *)task {
    NSHTTPURLResponse *response = (NSHTTPURLResponse*)task.response;
    //通讯协议状态码
    NSInteger statusCode = response.statusCode;
    return statusCode;
}



#pragma mark-- 请求串 MD5
-(NSString *)dictionaryToMD5:(NSDictionary *)dict addTimesStr:(NSString *)timeStr{
    
    NSMutableDictionary *parameters=[NSMutableDictionary dictionary];
    [parameters addEntriesFromDictionary:dict];
    
//    [parameters setValue:@"IJeHzP3EwFqdZYErHChCKpkmdkJCofLw" forKey:@"PublicKey"];
//    [parameters setValue:timeStr forKey:@"Timestamp"];
//    [parameters setValue:@"iOS" forKey:@"Platform"];
//
  
    
    NSMutableString *queryStr=[NSMutableString string];
    
    NSArray *sortedKeys = [[parameters allKeys] sortedArrayUsingSelector: @selector(compare:)];
    
    for (NSString *aKey in sortedKeys) {
        [queryStr appendFormat:@"%@=%@",aKey,[parameters objectForKey:aKey] ];
        [queryStr appendString:@"&"];
    }
    NSRange range = NSMakeRange(0,([queryStr length]-1));
    NSString *_tem= [queryStr substringWithRange:range];
    
    return [self md5:_tem];
}
#pragma mark --字符串排序
- (NSString *)StringSort:(NSDictionary *)dict{
    
    
    NSDictionary *temDic=[NSDictionary dictionaryWithDictionary:dict];
    NSMutableString *queryStr=[NSMutableString string];
    
    NSArray *sortedKeys = [[temDic allKeys] sortedArrayUsingSelector: @selector(compare:)];
    
    for (NSString *aKey in sortedKeys) {
        [queryStr appendFormat:@"%@=%@",aKey,[dict objectForKey:aKey] ];
        [queryStr appendString:@"&"];
    }
    NSRange range = NSMakeRange(0,([queryStr length]-1));
    NSString *_tem= [queryStr substringWithRange:range];
    
    return _tem;
    
}


#pragma mark MD5计算
- (NSString *)md5:(NSString *)str{
    
    
    //要进行UTF8的转码
    const char* input = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(input, (CC_LONG)strlen(input), result);
    
    NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [digest appendFormat:@"%02x", result[i]];
    }
    
    return digest;
    
    
}



#pragma ---字典转json字符串

//字典转字符串
- (NSString *)dictionaryToString:(NSDictionary *)dictionary{
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
    NSString *s = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    return s;
    
}

@end
